String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};

$(document).ready(function () {
    var animationSpeed = 300;
    var menu = '.sidebar';
    var methond = {
        init: function () {

            $('#navbar-collapse').click(function (e){
                if ($('#navbar-header-collapse').hasClass('on')) {
                    $('#navbar-header-collapse').removeClass('on');
                }  else {
                    $('#navbar-header-collapse').addClass('on');
                }
            });

            $('#navbar-header-collapse li.dropdown').click(function (e){
                if ($(window).width()<=768) {
                    if ($(this).hasClass('on')) {
                        $(this).removeClass('on');
                    } else {
                        $(this).addClass('on');
                    }
                }
            });

            $('.search-kw-input').focus(function (e) {
                if ($('.search-kw-input').val() != '') {
                    $('.fa-remove').show();
                }
            });

            $('.search-kw-input').hover(function (e) {
                if ($('.search-kw-input').val() != '') {
                    $('.fa-remove').show();
                }
            });

            $('#search').hover(function (e) {
            }, function (e) {
                $('.fa-remove').hide();
            });

            $('.search-kw-input').blur(function (e) {
                setTimeout(function () {
                    $('.fa-remove').hide();
                }, 300);
            });

            $('.fa-search').click(function (e) {
                methond.searchResult();
            });

            $('.search-kw-input').keyup(function (e) {
                if (e.keyCode == 13) {
                    methond.searchResult();
                }
            });
            $('.fa-remove').click(function (e) {
                $('.search-kw-input').val('');
                $(this).hide();
                if ($('.sitemap').length>0){
                    $('.sitemap .container .row > div').show();
                } else {
                    $('.nav_middle').show();
                    $('#fixed_nav .search').removeClass('on');
                    $('.nav_middle_search').hide();
                }
                return false;
            });
            if (this[action]) {
                this[action]();
            } else if (action==='rewrite_document') {
                this.document();
            }

        },
        searchResult: function () {
            if ($('.nav_left').length>0) {
                if ($('.search-kw-input').val() == '') {
                    return;
                }
                // 查找详情
                $.post(url_check_page, {
                    project_id: project_id,
                    search: $('.search-kw-input').val()
                }, function (data) {
                    if (data.code == 1) {
                        $('.nav_middle').hide();
                        $('.search_list .no_item').hide();
                        $('.search_list .items').hide();
                        $('.nav_middle_search').show();
                        $('#fixed_nav .search').removeClass('on');
                        if (data.data.length == 0) {
                            $('.search_list .no_item').show();
                            return;
                        }
                        $('.search_list .items').empty().show();
                        var html = '';
                        for (let i = 0; i < data.data.length; i++) {
                            var d = data.data[i];
                            var item = $('#template_search_item').html();
                            item = item.format(d.id, d.title, d.content, d.belong, d.date,d.url);
                            html += item;
                        }
                        $('.search_list .items').append(html);
                    } else if (data.code == 0) {
                        layer.msg(data.msg, {time: 1000});
                    }
                });
            } else if ($('.sitemap').length>0){
                var eles = $('.sitemap .container a');
                var search = $('.search-kw-input').val();
                for (var i=0;i<eles.length;i++){
                    var title = $.trim($(eles[i]).text());
                    if (title.indexOf(search)==-1) {
                        $(eles[i]).parent().parent().hide();
                    } else {
                        $(eles[i]).parent().parent().show();
                    }
                }
            } else {
                // 查找文档
                window.location.href = url_list+'?search=' + encodeURIComponent($('.search-kw-input').val());
            }
        },
        document: function () {
            methond.expandMenu();
            $('body').on('click','#md',function (e){
                if ($(window).width()<=768) {
                    if ($('.nav_left').hasClass('on')) {
                        $('.nav_left').removeClass('on');
                    }
                }
            });
            $('#home_header i.fa-bars').click(function (e) {
                if ($('.nav_left').hasClass('on')) {
                    $('.nav_left').removeClass('on');
                } else {
                    $('.nav_left').addClass('on');
                }
            });

            $('#fixed_nav .list').click(function () {
                if ($(this).find('i').hasClass('show')){
                    $(this).find('i').removeClass('show');
                    $('.nav_right').removeClass('on');
                } else {
                    $(this).find('i').addClass('show');
                    $('.nav_right').addClass('on');
                }
            });

            $('#fixed_nav .search').click(function () {
                $('.nav_middle').hide();
                $('#fixed_nav .search').removeClass('on');
                $('.nav_middle_search').show();
            });

            $('.nav_middle_search .search_title .fa-arrow-circle-right').click(function () {
                $('.nav_middle').show();
                if ($('.search-kw-input').val()!=''){
                    $('#fixed_nav .search').addClass('on');
                }
                $('.nav_middle_search').hide();

            });

            $('.nav_btn.style').click(function () {
                if ($(this).find('i').hasClass('fa-lightbulb-o')) {
                    // 白天切换到黑夜
                    $(this).find('i').removeClass('fa-lightbulb-o').addClass('fa-moon-o');
                    $('body').addClass('theme_dark');
                    methond.setCookie('style','night');
                } else {
                    $(this).find('i').removeClass('fa-moon-o').addClass('fa-lightbulb-o');
                    $('body').removeClass('theme_dark');
                    methond.setCookie('style','morning');
                }
            });

            $('.nav_btn.top').click(function () {
                methond.goTop(0, 500);
            });

            $('body').on('click', '.search_list .items .item', function (e) {
                var id = $(this).attr('id');
                var url = $(this).attr('url');
                if (url!='') {
                    window.location.href = url;
                    return false;
                }
                $('.nav_right').removeClass('on');
                $('.nav_btn.list i').removeClass('show');
                $('.sidebar-menu a').removeClass('active');
                $('a[data-id=' + id + ']').addClass('active');
                url = $('a[data-id=' + id + ']').attr('href');
                $('.nav_middle_search .search_title .fa-arrow-circle-right').trigger('click');
                methond.expandMenu();
                methond.requestUrl(url, function (url) {
                    // 修改浏览器地址
                    history.pushState({url}, '', url);
                });
            });

            // 文档页操作
            $(document).on('click', menu + ' li a', function (e) {
                    var x = e.pageX;
                    var y = e.pageY;
                    var that = this;
                     //打开新页面
                    // 一律走异步刷新
                    var url = $(this).attr('href');
                    if ($(this).parent().find('ul.treeview-menu').length>0) {
                       $(this).find('span.pull-right-container').trigger('click');
                    }
                    if (url.indexOf('javascript:;')!==-1) {
                         return;
                    }

                    if (x < 45 && $(this).hasClass('.menu_dir')) {
                        return false;
                    }

                    if ($(this).hasClass('menu_url')) {
                        return true;
                    }
                
                    $('.nav_middle_search .search_title .fa-arrow-circle-right').trigger('click');

                    if ($(this).hasClass('active')) {
                        return false;
                    }

                    page_id = $(this).attr('data-id');
                    $('.sidebar-menu a.active').removeClass('active');
                    $('.nav_right').removeClass('on');
                    $('.nav_btn.list i').removeClass('show');
                    $(that).addClass('active');
                    methond.requestUrl(url, function (url) {
                        // 修改浏览器地址
                        history.pushState({url}, '', url);
                    });

                    return false;
                });

            $(document).off('click', menu + ' li a>span.pull-right-container')
                .on('click', menu + ' li a>span.pull-right-container', function (e) {
                    //Get the clicked link and the next element
                    var $this = $(this).parent();
                    var checkElement = $this.next();
                    //Check if the next element is a menu and is visible
                    if ((checkElement.is('.treeview-menu')) && (checkElement.is(':visible'))) {
                        if ($("body").hasClass("sidebar-collapse") && $this.parent().parent().hasClass("sidebar-menu")) {
                            return false;
                        }
                        //Close the menu
                        checkElement.slideUp(animationSpeed, function () {
                            checkElement.removeClass('menu-open');
                            //Fix the layout in case the sidebar stretches over the height of the window
                            //_this.layout.fix();
                        });
                        // checkElement.parent("li").removeClass("active");
                        checkElement.parent("li").removeClass('treeview-open').removeClass('active');
                    }
                    //If the menu is not visible
                    else if ((checkElement.is('.treeview-menu')) && (!checkElement.is(':visible'))) {
                        //Get the parent menu
                        var parent = $this.parents('ul').first();
                        // modified by FastAdmin 保证只展开一项
                        if (false && $(".show-submenu", menu).length == 0) {
                            //Close all open menus within the parent
                            var ul = parent.find('ul:visible').slideUp(animationSpeed);
                            //Remove the menu-open class from the parent
                            ul.removeClass('menu-open');
                            parent.find('li.treeview').removeClass("treeview-open");
                        }
                        //Get the parent li
                        var parent_li = $this.parent("li");

                        //Open the target menu and add the menu-open class
                        checkElement.slideDown(animationSpeed, function () {
                            //Add the class active to the parent li
                            checkElement.addClass('menu-open');
                            //parent.find('li.active').removeClass('active');
                            //parent_li.addClass('active');
                            //Fix the layout in case the sidebar stretches over the height of the window
                            // _this.layout.fix();
                        });
                        parent_li.addClass('treeview-open');
                    } else {
                        if (!$this.parent().hasClass("active")) {
                            // $this.parent().addClass("active");
                        }
                        // modified by FastAdmin
                        if ($(".show-submenu", menu).length == 0 && $this.parent().parent().hasClass("sidebar-menu")) {
                            $this.parent().siblings().find("ul.menu-open").slideUp();
                            $this.parent().siblings("li.treeview-open").removeClass("treeview-open");
                        }
                    }
                    //if this isn't a link, prevent the page from being redirected
                    if (checkElement.is('.treeview-menu')) {
                        e.preventDefault();
                    }
                    return false;
                    e.stopPropagation();
                });
            //滚动条
            //$(".sidebar").slimScroll({destroy: true}).height("auto");
            $('.sidebar').slimScroll({
                //height: '550px'
                height: $(window).height() - 80
            });

            $('body').on('click', '#startVisit', function (e) {
                var password = $('#password').val();
                if (password == '') {
                    layer.msg('请输入密码', {time: 1000});
                    return false;
                }
                $.post(url_check_password, {
                    project_id: project_id,
                    id: page_id,
                    password: password
                }, function (data) {
                    if (data.code == 1) {
                        // methond.setCookie('page_password_' + page_id, password);
                        // if (window.location.href.indexOf('/document_item/') != -1) {
                        //     methond.setCookie('page_password_' + page_id, password);
                        // } else {
                        //     methond.setCookie('project_password_' + project_id, password);
                        // }
                        var url = $('a[data-id=' + page_id + ']').attr('href');
                        methond.requestUrl(url, function (url) {
                            // 修改浏览器地址
                            history.pushState({url}, '', url);
                        });
                        $('#password').val('');
                    } else if (data.code == 0) {
                        layer.msg('密码有误', {time: 1000});
                    }
                });
            });

            window.addEventListener('popstate', function (event) {
                // 当用户点击浏览器的回退按钮时，可以在这里加载新内容
                // event.state 可以获取到pushState或replaceState时设置的state对象
                if (event && event.state && event.state.url) {
                    methond.requestUrl(event.state.url);
                    $('.sidebar-menu a.active').removeClass('active');
                    $('a[href="' + event.state.url + '"]').addClass('active');
                }
            });
            var url ;
            if (static_cdn_type==0) {
                url = '/assets/addons/knowbase/js/index.min.js';
            } else if (static_cdn_type==1) {
                url = 'https://unpkg.com/vditor@3.10.4/dist/index.min.js';
            } else if (static_cdn_type==2) {
                url = 'https://s4.zstatic.net/npm/vditor@3.10.4/dist/index.min.js';
            }
            methond.loadScript(url,function (){
                methond.initPreview();
            });
            // 生成图标
            var url_eles = $('.menu_url');
            for (let i = 0; i <url_eles.length ; i++) {
                $(url_eles[i]).attr('target','_blank');
                $(url_eles[i]).find('span:eq(0)').after('<i class="fa fa-external-link" style="padding-left: 5px;"></i>');
                // $(url_eles[i]).find('i').addClass('fa fa-external-link');
            }
        },
        requestUrl: function (url, callback) {
            $.post(url, {}, function (data) {
                if (data.code == 1) {
                    $('.password_confirm').hide();
                    $('.nav_middle').removeClass('div-blur');
                    $('.nav_right').removeClass('div-blur');
                    $(document).prop('title', title.format(data.data.title));
                    $('.page_title').text(data.data.title);
                    $('.page_modify span').text(data.data.updatetime);
                    $('#md').text(data.data.content).hide();
                    $('#outline').empty();
                    methond.initPreview();
                    if (callback && typeof callback === 'function') {
                        callback(url);
                    }
                } else if (data.code == 0) {
                    if (data.data.code == 100) {
                        $('.nav_middle').addClass('div-blur');
                        $('.nav_right').addClass('div-blur');
                        $('.password_confirm').show();
                    } else if (data.data.code == 101) {
                        $('.nav_middle').addClass('div-blur');
                        $('.nav_right').addClass('div-blur');
                        layer.alert(data.msg);
                    } else if (data.data.code == 102) {
                        $('.nav_middle').addClass('div-blur');
                        $('.nav_right').addClass('div-blur');
                        //询问框
                        layer.confirm(data.msg, {
                            btn: ['前往登录','算了'] //按钮
                        }, function(){
                            window.location.href = '/index/user/login.html?url='+encodeURIComponent(data.url);
                        }, function(){
                            
                        });
                    }
                }
            });
        },
        initPreview: function () {
            //初始化markdown
            var url ;
            if (static_cdn_type==0) {
                url = '/assets/addons/knowbase';
            } else if (static_cdn_type==1) {
                url = 'https://unpkg.com/vditor@3.10.4';
            } else if (static_cdn_type==2) {
                url = 'https://s4.zstatic.net/npm/vditor@3.10.4';
            }
            var md = Vditor.preview(document.getElementById('md'), $('#md').text(), {
                'cdn': url,
                speech: {
                    enable: true,
                },
                theme: {
                    current: content_theme
                },
                hljs: {
                    enable: true,
                    style: code_theme,
                    lineNumber: code_show_number == 1 ? true : false
                },
                markdown:{
                    sanitize:true
                },
                anchor: 1,
                lazyLoadImage: loading,
                after() {
                    $('#md').show();
                    // if (window.innerWidth <= 768) {
                    //   return;
                    // }
                    const outlineElement = document.getElementById('outline');
                    Vditor.outlineRender(document.getElementById('md'), outlineElement);
                    if (outlineElement.innerText.trim() !== '') {
                        outlineElement.style.display = 'block';
                        methond.initOutline();
                        $('#outline').slimScroll({
                            height: '500px'
                        });
                        $('#fixed_nav .list').addClass('on');
                    } else {
                        $('#fixed_nav .list').removeClass('on');
                    }
                    // 图片居中
                    $('#md img').parent().css({'text-align': 'center'});
                    $('#md audio').parent().css({'text-align': 'center'});
                    $('#md video').parent().css({'text-align': 'center'});
                    //$('#md a:not([href*="javascript:"])').attr('target','_blank');
                    $('#md a').filter(function () {
                        return this.href.indexOf('javascript:') === -1 && this.href.indexOf('#') === -1;
                    }).each(function () {
                        $(this).attr('target', '_blank');
                    });

                    $('#md img').off().on('click', function (event) {
                        Vditor.previewImage(event.target, 'zh_CN', 'classic');
                    });
                }
            });
        },
        initOutline: function () {
            var headingElements = [];
            var children = document.getElementById('md').children;
            for (var i = 0, len = children.length; i < len; i++) {
                var item = children[i];
                if (item.tagName.length === 2 && item.tagName !== 'HR' && item.tagName.indexOf('H') === 0) {
                    headingElements.push(item);
                }
            }

            var toc = [];
            window.addEventListener('scroll', function () {
                var scrollTop = window.scrollY;
                toc = [];
                for (var j = 0, lenJ = headingElements.length; j < lenJ; j++) {
                    var item = headingElements[j];
                    toc.push({
                        id: item.id,
                        offsetTop: item.offsetTop
                    });
                }

                var currentElement = document.querySelector('.vditor-outline__item--current');
                for (var k = 0, lenK = toc.length; k < lenK; k++) {
                    if (scrollTop < toc[k].offsetTop - 30) {
                        if (currentElement) {
                            currentElement.classList.remove('vditor-outline__item--current');
                        }
                        var index = k > 0 ? k - 1 : 0;
                        document.querySelector('span[data-target-id="' + toc[index].id + '"]').classList.add('vditor-outline__item--current');
                        break;
                    }
                }

                if (scrollTop > 200) {
                    $('.nav_btn.top').show();
                } else {
                    $('.nav_btn.top').hide();
                }

            });
        },
        expandMenu: function (parent) {
            var ul;
            var li;
            if (parent == null) {
                var ele = $('a.active');
                if (ele.length == 1) {
                    ele.parent().addClass('treeview-open');
                    ul = ele.parent().parent();
                    ul.addClass('menu-open');
                    methond.expandMenu(ul);
                }
            } else {
                li = parent.parent();
                if (li.length == 1 && li.prop('tagName').toLowerCase() == 'li') {
                    li.addClass('treeview-open');
                    ul = li.parent();
                    ul.addClass('menu-open');
                    methond.expandMenu(ul);
                }
            }
        },
        setCookie: function (name, value) {
            var Days = 7;
            var exp = new Date();
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + exp.toGMTString();
        },
        goTop: function (top, time) {
            if (top == undefined) {
                top = 0;
            }

            if (time == undefined) {
                time = 600;
            }
            $('html,body').animate({'scrollTop': top}, time);
        },
        loadScript:function (e, s,r) {
            var i = document.createElement("script");
            i.src = e, i.async = !0, document.head.appendChild(i), i.onerror = function(error) {
                r(error);
            }, i.onload = function() {
                 s();
            }
        }
    };
    methond.init();
});
